<template>
  <div>
    <!-- 嵌套表 -->
    <el-dialog :title="dialogTitle" :visible="dialogVisible" @close="dialogClose">
      <el-form :model="stuForm" :rules="stuRules" ref="addStuRuleForm">
        <el-form-item label="头像">
          <el-upload
            class="uploadAvatar"
            ref="uploadAvatar"
            action="https://chst.vip/students/uploadStuAvatar"
            list-type="picture-card"
            name="headimgurl"
            :multiple="false"
            :file-list="headimgList"
            :on-success="uploadSuccess"
            :on-remove="removeAvatar"
            :limit="limit"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="stuForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="项目地址" prop="productUrl">
          <el-input v-model="stuForm.productUrl" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="class">
          <el-input v-model="stuForm.class" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="stuForm.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="stuForm.city" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学历" prop="degree">
          <el-input v-model="stuForm.degree" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input v-model="stuForm.description" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="HIDE_DIALOG">取 消</el-button>
        <el-button type="primary" @click="confirmClick('addStuRuleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import * as api from "@/api/users";
export default {
  computed: {
    ...mapState(["dialogVisible", "dialogTitle", "currentRow"]),
  },
  data() {
    return {
      limit: 1, //上传文件的数量
      headimgList: [], //回显头像
      dialogTableVisible: false,
      // dialogVisible: true,
      stuRules: {
        name: [{ required: true, message: "请输入名字", trigger: "blur" }],
        class: [{ required: true, message: "请输入班级", trigger: "blur" }],
        degree: [{ required: true, message: "请输入学历", trigger: "blur" }],
        city: [{ required: true, message: "请输入城市", trigger: "blur" }],
        productUrl: [
          { required: true, message: "请输入项目地址", trigger: "blur" },
        ],
        age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
        description: [
          { required: true, message: "请输入描述", trigger: "blur" },
        ],
      },
      // stuForm: {
      //   name: "",
      //   region: "",
      //   date1: "",
      //   date2: "",
      //   delivery: false,
      //   type: [],
      //   resource: "",
      //   desc: "",
      // },
      stuForm: {
        name: "",
        productUrl: "",
        headimgurl: "",
        class: "",
        age: "",
        city: "",
        degree: "",
        description: "",
      },
      oldForm: {}, //储存stuForm的初始值,便于清空dialog的内容
      formLabelWidth: "120px",
    };
  },
  methods: {
    ...mapMutations(["SHOW_DIALOG", "HIDE_DIALOG", "CHANGE_DIALOG_TITLE"]),
    ...mapActions(["GET_STULIST"]),
    confirmClick(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.HIDE_DIALOG();
          //表单验证成功
          //发送请求 问题：如何知道点击确定的时候，此时请求添加接口还是编辑接口
          //判断dialogTitle
          if (this.dialogTitle == "增加学员信息") {
            //发起请求
            // console.log(this.stuForm);
            api.addStuApi(this.stuForm).then((res) => {
              // console.log(res);
              if (res.data.state) {
                //增加成功
                this.GET_STULIST();
                this.$message.success('添加成功')
              } else {
                //增加失败
                this.$message.error("增加失败");
              }
            });
          } else {
            //发起编辑请求
            api.updateStuApi(this.stuForm).then((res) => {
              // console.log(res);
              if (res.data.state) {
                //修改成功，更新视图
                this.GET_STULIST();
                this.$message.success('修改成功')
              } else {
                //更新失败，比如你更新的时候，这条数据被别人删除了，更新失败
                this.$message.error("更新失败，没有做任何修改，或者数据不存在！");
                this.GET_STULIST()
              }
            });
          }
        } else {
          this.$message.error("请将内容填写完整");
        }
      });
    },
    dialogClose() {
      // this.oldForm
      this.HIDE_DIALOG();
      //清空dialog表单数据
      this.stuForm = this.oldForm;
      //清空回显头像的数组
      this.headimgList = [];
      this.limit = 1;
    },
    uploadSuccess(r) {
      console.log(r);
      if (r.state) {
        this.stuForm.headimgurl = r.headimgurl;
        console.log(this.headimgList);
        if (this.dialogTitle === "编辑学员信息") {
          //把headimgList列表内容设为当前项
          this.headimgList = [{ url: r.headimgurl }];
        }
      } else {
        this.$message.error("上传失败");
      }
    },
  },
  created() {
    this.oldForm = { ...this.stuForm }; //储存stuForm的初始值
  },
  watch: {
    currentRow(newVal) {
      //监听传入的row的数据变化
      // console.log(newVal);
      //如果dialogTitle等于编辑学员信息那么就做数据回显

      // console.log(this.currentRow);
      // console.log(this.stuForm);
      this.stuForm = this.currentRow;
      //回显头像
      this.headimgList = [{ url: this.currentRow.headimgurl }];
      //编辑的时候让limit=2
      this.limit = 2;
    },
  },
};
</script>
<style scoped lang="less">
/deep/ el-dialog {
  text-align: center;
}
</style>

<!-- <script>
import { mapState,mapMutations,mapActions } from 'vuex';
import * as api from "../../api/users"
export default {
  computed:{
    ...mapState(['dialogVisible','dialogTitle','currentRow'])
  },
  methods:{
    ...mapMutations(["SHOW_DIALOG","HIDE_DIALOG","CHANGE_DIALOG_TITLE"]),
    ...mapActions(["GET_STULIST"]),
    dialogClose(){
      //清空输入框的值
      this.HIDE_DIALOG();

      //清空dialog表单数据
      this.stuForm={...this.oldFrom}

      //清空回显头像的数据
      this.headimgList=[];
      this.limit=1;
    },
    uploadSuccess(r){
      if(r.state){
        this.stuForm.headimgurl = r.headimgurl;
        console.log(this.headimgList);
        if(this.dialogTitle==="编辑学员信息"){
          setTimeout(()=>{
            //将headimgList列表内容设置为当前项
            this.headimgList = [{url:r.headimgurl}]
          },500)
        }
      }else{
        this.$message.error("上传失败")
      }
    },
    removeAvatar(r){},
    confirmClick(formName){
      this.$refs[formName].validate((valid)=>{
        if(valid){
          this.HIDE_DIALOG();

          //发起请求
          //判断dialogTitle
          if(this.dialogTitle==="增加学员信息"){
            api.addStuApi(this.stuForm).then((res)=>{
              if(res.data.state){
                this.GET_STULIST();
                this.$message.success("添加成功")
              }
            });
          }else{
            api.updateStuApi(this.stuForm).then((res)=>{
              if(res.data.state){
                //修改成功，更新视图
                this.GET_STULIST();
                this.$message.success("修改成功")
              }else{
                //更新失败
                this.$message.error("更新失败，没做任何修改，或者数据不存在");
                this.GET_STULIST();
              }
            })
          }
        }else{
          this.$message.error("请将内容填写完整")
        }
      })
    }

  },
  created(){
    this.oldFrom={...this.stuForm}
  },
  watch: {
    currentRow(newVal){
      this.stuForm=this.currentRow;
      this.headimgList=[{url:this.currentRow.headimgurl}];
      this.limit=2
    }
  },
  data() {
    return {
      showAvatar: true,
      headimgList:[],
      limit:1, 
      stuForm: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      // oldFrom:{},
      // dialogVisible: true, //控制显示隐藏
      stuRules: {
        name: [{ required: true, message: "请输入名字", trigger: "blur" }],
        class: [{ required: true, message: "请输入班级", trigger: "blur" }],
        degree: [{ required: true, message: "请输入学历", trigger: "blur" }],
        city: [{ required: true, message: "请输入城市", trigger: "blur" }],
        productUrl: [
          { required: true, message: "请输入项目地址", trigger: "blur" },
        ],
        age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
        description: [
          { required: true, message: "请输入描述", trigger: "blur" },
        ],
      },
    };
  },
};
</script>
<style scoped>
.el-form-item {
  text-align: left;
}
</style> -->